<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8" session="false" %>
<%@ page import="com.atozsoft.commonutil.Constants"%>
<%@ page import="java.util.Date"%>
<%@ page import="java.text.SimpleDateFormat"%>
<%@page import="com.eos.data.datacontext.UserObject"%>	
<%@ page import="commonj.sdo.DataObject"%>
	
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<!-- 
  - Author(s): houfy
  - Date: 2014-11-20 17:12:31
  - Description:
-->
<head>
<title>流程执行</title>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    
    <%@include file="/common.jsp"%>
	<%@include file="/common/common.jsp"%>
    <%@include file="/coframe/tools/skins/common.jsp" %>
    <%
      // 设置上传文件路径
		Date date = new Date();
	    SimpleDateFormat formatStr = new SimpleDateFormat("yyyyMMdd");        
	    String strDate = formatStr.format(date); 
    	//String targetPath =absolutePath + Constants.UPLOADPATH +"process/"+strDate+"/";
    	
    	//流程实例ID
 	 	String processInstId = "";
		if(request.getParameter("processInstId")!=null){
			processInstId = (String)request.getParameter("processInstId");
		}
		String workitemid = "";	
		if(request.getParameter("workitemid")!=null){
			workitemid = (String)request.getParameter("workitemid");
		}
		
		//操作类型
		String operateType = "";
		if(request.getParameter("operateType")!=null){
			operateType = (String)request.getParameter("operateType");
		}
		
		String processDataType = ""; //判断数据类型是转发、抄送、加审
		if(request.getParameter("processDataType")!=null){
			processDataType = (String)request.getParameter("processDataType");
		}
		
		String workTypes = ""; //判断页面字段加载
		if(request.getParameter("workType")!=null){
			workTypes = (String)request.getParameter("workType");
		}
		
		//是否跳过下个节点
		String leaderCheck = "0";
		if(request.getParameter("leaderCheck")!=null){
			leaderCheck = (String)request.getParameter("leaderCheck");
		}
		
		//选择下一审批人
		String isSelect = "";
		if(request.getParameter("isSelect")!=null){
			isSelect = (String)request.getParameter("isSelect");
		}
		
		UserObject userObject = (UserObject)request.getSession().getAttribute("userObject");
		DataObject capUser = (DataObject)userObject.get("orgUser");
		// 登陆者所属BU
		String operatorId = capUser.getString("operatorid");
		String userId = userObject.getUserId();
     %>
</head>
<body>
	<div id="updateProcessExamineForm">
		<table class="table"  border="0" style="width:100%;">
			<tr id="returnArea"  style="display:none">
			    <th class="nui-form-label"><font color="red">*</font>&nbsp;回退节点：</th>
				<td>
				    <input id="returnworkitemid"  name="returnworkitemid"  class="nui-buttonedit  nui-form-input" emptyText="请选择..."  onbuttonclick="selectWorkItem" selectOnFocus="true" required="true" requiredErrorText="回退节点不能为空！" />
				</td>
        	</tr>
        	<tr id="rollbackArea"  style="display:none">
			    <th class="nui-form-label"><font color="red">*</font>&nbsp;提示：</th>
				<td>
				    	运行位置：<input id="currentWorkItem" name="currentWorkItem" class="nui-textbox asLable" value="" style="width:30%;" allowInput="false"/>
				    			 <input id="currnetWrokItemid" name="currnetWrokItemid" class="nui-hidden">
				    	，
				    	当前位置：<input id="nowWorkItem" name="nowWorkItem" class="nui-textbox asLable" value="" style="width:30%;" allowInput="false"/>
				    			 <input id="nowWrokItemid" name="nowWrokItemid" class="nui-hidden">
				    			 <!-- 新增下面一行代码 -->
				    			 <input id="activityDefID" name="activityDefID" class="nui-hidden">
				    			 <input id="processDefID" name="processDefID" class="nui-hidden">
				</td>
        	</tr>
        	<tr id="stopArea" style="display:none">
				<td class="nui-form-label"><a class="nui-button" iconCls="icon-tip" plain="true"></a></td>
				<td>
				   <font style="font-weight: bold;color:red">警告：流程将被终止！</font>
				</td>
        	</tr>
        	<tr id="selectuserArea" style="display:none">
			    <th class="nui-form-label"><font color="red">*</font>&nbsp;参与人员：</th>
				<td>
				    <input id="salesmanid"  required="true" requiredErrorText="参与人员不能为空！" class="nui-buttonedit nui-form-input" name="tradercustomer.salesmanid" allowInput="false" emptyText="请选择..." onbuttonclick="onOrgEmployeeBtn"/>
				</td>
        	</tr>  
			<!-- <tr id="suggest">
				<th class="nui-form-label">&nbsp;常用意见：</th>
				<td >
				    <input id="remark"  name="remark" class="nui-combobox nui-form-input" textField="remark" valueField="oftenopinionid" emptyText="请选择..." dataField="datas"
 							    onvaluechanged="valuechanged"	url="com.atozsoft.wf.common.queryProcessOftenOpinion.biz.ext"  showClose="true" oncloseclick="onCloseClick"  allowInput="false" showNullItem="true" nullItemText="请选择..."/>     
				</td>
			</tr> -->
			<tr id="suggest">
				<th class="nui-form-label">&nbsp;常用意见：</th>
				<td >
				    <input id="remark"  class="nui-dictcombobox nui-form-input" style="width:100%;" name="remark"  allowInput="false" dictTypeId="NOMAL_ADVISE"  />     
				</td>
			</tr>
			<tr id="suggestDetail">
				<th class="nui-form-label"><font color="red">*</font>&nbsp;处理意见：<br><a  class="nui-button" iconCls="icon-add"  id="addoftenopinionBtn" onclick="addoftenOpinion()" plain="true" tooltip="添加为常用意见"></a> </th>
				<td ><input id="approvent" name="approvent" required="true" requiredErrorText="处理意见不能为空！" class="nui-textarea nui-form-input" value="" style="height:80px;"/></td>
			</tr>
			<tr id="workhoursArea" style="display:none">
				<th class="nui-form-label">&nbsp;工时(H)：</th>
				<td >
				    <input id="workhours"  name="workhours" class="nui-spinner nui-form-input" value="0.00" decimalPlaces=2 minValue="0" maxValue="10000" />     
				</td>
			</tr>
			<tr id="upload" style="display:none">
			    <th>
			    </th>
			    <td>
				    <div style="width:100%;padding:2px 0px 0px 0px;">
						<div class="nui-toolbar" style="border-bottom:0;">
				        	<table style="width:100%;">
				            	<tr>
						            <td style="width:50%;">
						                <a class="nui-button" id="uploadify">上传</a>
						            	<a id="deleteFile" class="nui-button" onclick="removeFile()" style="margin-left: 85px; width:60px;">删除</a>
						            </td>
					            </tr>
					        </table>
				    	</div>
				    </div>
				    <div class="nui-fit" style="width:100%;min-height:81px;height:82px;">
					    <div id="attachmentDatagrid" class="nui-datagrid" style="width:100%;height:99%" 
				    	     idField="id" dataField="crmFiles" url="com.atozsoft.crm.common.queryUplodeFileListByIds.biz.ext"
				    	     sizeList="[5,10,20,50]" pageSize="5" allowResize="false" showPager="false"
				    	     showReloadButton="false" totalField="total" multiSelect="true">
				             <div property="columns">
				                <div field="fileid" visible="false"></div>
				                <div field="filepath" visible="false"></div>
				          		<div type="checkcolumn" headerAlign="center" width="10px" align="center"></div>
						        <div type="indexcolumn" headerAlign="center" width="20px" align="center">序号</div>
						        <div field="uploadname" headerAlign="center" allowSort="true" renderer="renderOnfileName" >上传名称</div>
						    </div>
					    </div>
				    </div>
			    </td>
			</tr>
		</table>	
		<div class="nui-toolbar" style="padding:0px;" borderStyle="border:0;">
			<table width="100%">
				<tr>
					<td style="text-align:center;">
						<a class="nui-button" iconCls="icon-save" onclick="onOk">保存</a>
						<span style="display:inline-block;width:25px;"></span>
						<a class="nui-button" iconCls="icon-cancel" onclick="onCancel">取消</a>
					</td>
				</tr>
			</table>
		</div>
	</div>
	 <script type="text/javascript">
        nui.parse();
        var operateType   = "<%=operateType %>";
        var processInstId = '<%=processInstId %>';
        var workitemid    = '<%=workitemid %>';
        var userid        = "";
        var username      = "";
        var processDataType = "<%=processDataType %>";
        var isSelect = "<%=isSelect %>";
        var checkerid = "";
        
        //工时显示控制,不限制加载类型
    	var workTypedata = <%=workTypes%>;
    	if(workTypedata == "01"){
    		document.getElementById("workhoursArea").style.display = "";
    	} 
        
        //判断操作，确定显示字段
        if(operateType == "agreeHandle"){//加审操作        
        	nui.get("approvent").setValue("同意");
        }else if(operateType == "returnstepHandle"){ //退回操作
        	document.getElementById("returnArea").style.display = "";
        	document.getElementById("suggest").style.display = "none";
        	document.getElementById("suggestDetail").style.display = "none";
        }else if(operateType == "rollbackHandle"){  //撤回操作
        	showProcessWorkItemBePlay(); //获取当前流程实例的实际工作项
			showProcessWorkItem();	//获取当前工作项名称
        	document.getElementById("rollbackArea").style.display = "";
        }else if(operateType == "stopHandle"){//终止操作
        	document.getElementById("stopArea").style.display = ""; 	
        }else if(operateType == "forwardHandle"){//转发操作
        	document.getElementById("selectuserArea").style.display = "";
        }else if(operateType == "CopytoHandle"){//抄送操作        	
        	document.getElementById("selectuserArea").style.display = "";
        }
        
        var form = new nui.Form("#updateProcessExamineForm");
        var grid = nui.get("attachmentDatagrid");
        var result = true; //用于表示 审批意见是否保存成功
        
        //保存
		function onOk(){
			if(isSelect!=null&&isSelect!=""&&isSelect!="null") {
				nui.open({
		            url: "<%=request.getContextPath()%>/mis/orgUser/selectEmployee.jsp?processInstId=" + processInstId+ "&workitemid="+workitemid+"&empid=N&role=" + isSelect,
			        title: "审批者选择",
			        width: 870,
                	height: 550,
	                ondestroy: function (action) {
		            	if(action=="ok"){
		             		var iframe = this.getIFrameEl();
	                        var data = iframe.contentWindow.GetData();
	                        data = nui.clone(data);    //必须克隆返回值
	                        // 审批人选定赋值
	                        checkerid = data.empid;  
	        				save(checkerid);
			            }
	                }
			    });
		    }else{
		    	save();
		    }
        }
        
        function save(checkerid){
        	form.validate();
            if(form.isValid()==false) return;
           
            // 得到附件id
	        var griddata = grid.getData();
	        var ids = [];
	        for(var i = 0;i<griddata.length;i++){
	          ids.push(griddata[i].fileid);
	        }
	        var approveObj = {};  //组合数据
	        var transmitObj = {};  //组合数据
	        approveObj.processinstid = processInstId;
	        approveObj.workitemid = workitemid;
	        approveObj.approvent = nui.get("approvent").getValue();
	        approveObj.workhours = nui.get("workhours").getValue();
	        //approveObj.leaderCheck = <%=leaderCheck %>;
	        approveObj.fileid = ids.join(",");
	        var strUrl = "";
	        var json = "";
	        
			//判断操作，确定传入参数
			//退回操作
			if(operateType == "returnstepHandle"){
				approveObj.approvetype = "1"; //退回=1
				var activityDefID = nui.get("returnworkitemid").getValue();
				approveObj.approvent = "退回";
	            var handleType = "";
	        	if(processDataType.indexOf("-") > 0){
	        	    var dataType = processDataType.split("-");
	        	    handleType = dataType[0];
		        	if("forward" == handleType){  //转发接收人操作
						transmitObj.executestatus = "1";  //执行状态
						transmitObj.transmitid = dataType[1]; //转发表ID
						transmitObj.creater = dataType[2]; //转发创建者
		        	}
	        	 }
				
		      	json = nui.encode({approveObj:approveObj,activityDefID:activityDefID,handleType:handleType});
		      	strUrl = "com.atozsoft.wf.processOperate.returnProcess.biz.ext";
			}else if(operateType == "rollbackHandle"){  //撤回操作
				approveObj.approvetype = "7"; //撤回=7
                //2015-10-15 18:16  wangy  修改：将下面注释的代码改为1的代码
				//approveObj.workitemid = nui.get("currnetWrokItemid").getValue();
				approveObj.workitemid = nui.get("nowWrokItemid").getValue();  //1
                //2015-10-15 18:50  wangy  修改：将下面注释的代码改为2的代码
				//var activityDefID = nui.get("nowWrokItemid").getValue();
				var activityDefID = nui.get("activityDefID").getValue();  //2
				var currentWIname = nui.get("currentWorkItem").getValue();
				var nowWIname = nui.get("nowWorkItem").getValue();
				if(currentWIname == nowWIname){
					nui.alert("当前位置与运行位置相同，不允许撤回！", "提示", function(action){
						if(action == "ok" || action == "close"){
							CloseWindow("cancel");
						}
					});
					return;
				}
				var handleType = "";
	        	if(processDataType.indexOf("-") > 0){
	        	    var dataType = processDataType.split("-");
	        	    handleType = dataType[0];
	        	 }
				
		      	json = nui.encode({approveObj:approveObj,activityDefID:activityDefID,handleType:handleType});
		      	strUrl = "com.atozsoft.wf.processOperate.rollbackProcess.biz.ext";
			}else if(operateType == "stopHandle"){//终止操作
				approveObj.approvetype = "8"; //终止=8
				
				var handleType = "";
	        	if(processDataType.indexOf("-") > 0){
	        	    var dataType = processDataType.split("-");
	        	    handleType = dataType[0];
	        	}
		      	json = nui.encode({approveObj:approveObj, handleType:handleType});
				strUrl = "com.atozsoft.wf.processOperate.stopProcess.biz.ext";
			}
	        else if(operateType == "agreeHandle"){//审批意见操作
	        	showProcessWorkItem();
				var activityDefID = nui.get("activityDefID").getValue();  //2
				var processDefID = nui.get("processDefID").getValue();  //流程定义ID
				var level = activityDefID.substr(activityDefID.length-1,1);
				var nodeTotal = 0;
				
	        	approveObj.approvetype = 2; //同意=2
	        	var handleType = "";
	        	if(processDataType.indexOf("-") > 0){
	        	    var dataType = processDataType.split("-");
	        	    handleType = dataType[0];
	        	}
		      	json = nui.encode({approveObj:approveObj,handleType:handleType});
		      	strUrl = "com.atozsoft.wf.processOperate.processAgreeAndForwardAndAddExamine.biz.ext";
	        }
	        else if(operateType == "forwardHandle"){//转发操作        	
        		approveObj.approvetype = "9"; //转发=4
				username = nui.get("salesmanid").getText();
				username = username.replace(/,/g, "|");
				approveObj.approvent = "接收人：" + username + ". " + approveObj.approvent;
				
				transmitObj.processinstid = processInstId;
		        transmitObj.workitemid = workitemid;
				var empid = nui.get("salesmanid").getValue();// 得到转发人Id
				
				var dataType = processDataType.split("-");
	        	var handleType = dataType[0];
				
		      	json = nui.encode({approveObj:approveObj,empid:empid,handleType:handleType});
		      	strUrl = "com.atozsoft.wf.processOperate.ProcessForward.biz.ext";
	        }	
	      
	      //alert("结果："+json);
	      if(checkerid != "" && checkerid != null){
	      	updateProcessInstParams(processInstId,"checkerid",checkerid);
	      }
	      //return;
	      $.ajax({
                url: strUrl,
                data: json,
                type: "post",
                cache: false,
                contentType:'text/json',
                beforeSend:loading(),
                success: function (text) {
                  endLoading();
                  if("fails" == text.result){
                     result = false;
                     nui.alert("下一审批环节启动失败（审批人为空），请联系管理员！");
                     return;
                  }else{
                    CloseWindow("ok");
                  }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    alert(jqXHR.responseText);
                }
            }); 
        }
		
		// 更新指定参数
		// 添加常用意见
		function updateProcessInstParams(processInstId,paramName,paramValue){
		    var Ujson = nui.encode({processInstId:processInstId,paramName:paramName,paramValue:paramValue});
		    //nui.alert(Ujson);
		    $.ajax({
		        url: "com.atozsoft.wf.processParticipant.updateProcessInstParams.biz.ext",
		        type: 'POST',
		        data: Ujson,
		        cache: false,
		        contentType: 'text/json',
		        beforeSend:loading(),
		        success: function (text) {
		            
		        }
		    });
		}
		
		// 取消按钮
	    function onCancel(){
	      var dataNum =  grid.getData().length;
	      if(dataNum > 0){
	       nui.alert("已上传附件，请先删除附件!");
	       return;
	      }
	      CloseWindow("cancel");
	    }
	    
		// 关闭窗体
		function CloseWindow(action){
		   if(window.CloseOwnerWindow) 
		    return window.CloseOwnerWindow(action);
		  else
		    return window.close();
		}
		
	   //选择意见
	   function valuechanged(e){
	    	var remark = nui.get("remark").getText();
	     	nui.get("approvent").setValue(remark);
	   } 
	   
	   //常用意见删除
	   function onCloseClick(){
			var oftenopinionid = nui.get("remark").getValue();
			if(oftenopinionid==null) return
			//nui.alert("oftenOponionId");
			nui.confirm("确认删除当前常用意见？","删除确认",function(action){
            	if(action!="ok") return;
  				var json = nui.encode({oftenopinionid:oftenopinionid});
                $.ajax({
                    url: "com.atozsoft.wf.common.deleteProcessOftenOpinion.biz.ext",
	                type: 'POST',
	                data: json,
	                cache: false,
	                contentType:'text/json',
	                beforeSend:loading(),
                    success: function (text) {
                    	endLoading();
                       	var returnJson = nui.decode(text);
                    	nui.get("remark").load("com.atozsoft.wf.common.queryProcessOftenOpinion.biz.ext");
                    	nui.get("approvent").setValue("");
                    	forms.reload();
						if(returnJson.resultStr != 'SUCCESS'){
                        	nui.alert("常用意见删除失败！", "提示");
                    	}
                    }
                });
            }); 
		 }
		 
		// 添加常用意见
		function addoftenOpinion() {
		    // 校验
		    var remark = nui.get("approvent").getValue();
		    if (remark == "" || remark==null) return;
		    var oftenOpinion = {};  //组合数据
	        oftenOpinion.processid = '<%=processInstId %>';
	        oftenOpinion.remark = remark;
		    var json = nui.encode({oftenOpinion:oftenOpinion});
		    $.ajax({
		        url: "com.atozsoft.wf.common.addProcessOftenOpinion.biz.ext",
		        type: 'POST',
		        data: json,
		        cache: false,
		        contentType: 'text/json',
		        beforeSend:loading(),
		        success: function (text) {
		            endLoading();
		            var response = text.result || "";
		            nui.get("remark").load("com.atozsoft.wf.common.queryProcessOftenOpinion.biz.ext");
		            if (response != "SUCCESS") {
		                nui.alert("添加常用意见失败！","提示");
		            }
		        }
		    });
		}
	    
	    //获取审批结果
	    function getData(){
	     return result;
	    }
	    
	    // 转发 - 人员选择
	   function onOrgEmployeeBtn(){
	   		var btnEdit = this;
	    	nui.open({
	            url: "<%=request.getContextPath()%>/crm/popup/selectEmp.jsp",
	        title: "选择抄送人员",
			width: 900, 
	        height: 500,
	        onload: function() {
	            var iframe = this.getIFrameEl();
	            //多选
	            //iframe.contentWindow.setData('true');
	            //获取代理人ID
	            var empids = nui.get("salesmanid").getValue();
	            //多选
	            iframe.contentWindow.setData('true',empids);
	        },
	        ondestroy: function (action) {
	           // 确定后返回勾选值
	           if (action == "ok") {
	                var iframe = this.getIFrameEl();
	                var data = iframe.contentWindow.getData();
	                data = nui.clone(data);    //必须克隆返回值
	                if (data) {
	                	var id = "";
	                	var name = "";
	                    for(var i = 0; i < data.length; i++){
	                    	id = id + data[i].operatorid + ",";
	                    	name = name + data[i].empname + ",";
	                    }
	                    
	                    // 设置返回值
	                    btnEdit.setValue(id.substring(0,id.length-1));
	                    btnEdit.setText(name.substring(0,name.length-1)); 
		            }
		        }
		    }
		    });
		}
		
		//获取当前流程实例的实际工作项
		function showProcessWorkItemBePlay(){
			var processInstId = "<%=processInstId %>";
        	var json = nui.encode({processInstId:processInstId});
	        $.ajax({
	            url: "com.atozsoft.wf.processOperate.queryProcessWorkItemBeplayByPid.biz.ext",
	            type: 'POST',
	            data:json,
	            cache: false,
	            async: false,
	            contentType: 'text/json',
	            success: function(text) {
	                var data = text.datas[0];
	                //nui.alert(data.workItemName);
	                nui.get("currentWorkItem").setValue(data.workItemName); 
	                nui.get("currnetWrokItemid").setValue(data.workItemID);
	          }
	        });
		}
		
		//获取当前工作项名称
		function showProcessWorkItem(){
			var workitemid = "<%=workitemid %>";
			//alert("workitemid===" + workitemid);
        	var json =nui.encode({workitemid:workitemid});
	        $.ajax({
	            url: "com.atozsoft.wf.processOperate.queryWorkItemById.biz.ext",
	            type: 'POST',
	            data:json,
	            cache: false,
	            async: false,
	            contentType: 'text/json',
	            success: function(text) {
	                var data = text.datas[0];
	                //nui.alert(data.activityDefID);
	                nui.get("nowWorkItem").setValue(data.workItemName); 
	                //2015-10-15 18:16  wangy  修改：将下面注释的代码改为1的代码  并新增2的代码
	                //nui.get("nowWrokItemid").setValue(data.activityDefID);
	                nui.get("nowWrokItemid").setValue(data.workItemID);   //1
	                nui.get("activityDefID").setValue(data.activityDefID);   //2
	                nui.get("processDefID").setValue(data.processDefID);   //流程定义ID
	                //alert("data.activityDefID===" + data.activityDefID);
	          }
	        });
		}
		
		//回退工作想选择
		function selectWorkItem(e) {
            	var btnEdit = this;
	    	var zoomvalue = 1;
	    	nui.open({
	            url: "<%=request.getContextPath()%>/wf/common/showWFGraph_popup.jsp?processInstId=<%=processInstId %>&zoomvalue=" + zoomvalue,
		        title: "退回",
				width: 680, 
		        height: 630,
		        onload: function() {
		        },
		        ondestroy: function (action) {
					if (action == "ok"){
						var iframe = this.getIFrameEl();
	                    var data = iframe.contentWindow.GetData(); //接收选中的按钮信息
	                    data = nui.clone(data);
	                    if(data){
	                    	var defineid = data;
	                    	var workiteminfo = defineid.split("_");
	                    	var workitemid = workiteminfo[0] + "_" + workiteminfo[1];
	                    	nui.get("returnworkitemid").setText(workiteminfo[2]); 
	                		nui.get("returnworkitemid").setValue(workitemid);
	                		//nui.alert(workitemid);
	                    }
					}
	             }
		    });
        }
        
        /**
         * 获取返回选择行
         */
		function getNextUserData(){
			//nui.alert(username);
			return username;
		}
		
		//等待提示
		function loading(){nui.mask({el: document.body,cls: 'mini-mask-loading',html: '处理中...'});}
	    function endLoading(){nui.unmask(document.body);}
		
    </script>
</body>
</html>